<?php

namespace App\Service\OpenShop\Feishu;


use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Rms\RmsUserApi;
use App\Models\Feishu\FsLoginLogModel;
use App\Support\AppletEncrypt;
use Illuminate\Support\Facades\Log;

class AppletLoginService
{

    public static function getSiteFeishuConfig($platformName)
    {
        $config = ConfigService::config('feishu', 'appIdList');
        $config = array_column($config["appIdList"], null, 'platformName');
        return $config[$platformName];
    }

    public static function loginByFeishuCode(string $feishuCode, $siteConfig, string $ip)
    {
        $baseInfo    = FeishuApiService::loginByCode($feishuCode, $siteConfig);
        Log::info("loginByFeishuCode Start feishuCode:{$feishuCode}", [$siteConfig, $baseInfo]);
        $msg         = $baseInfo['msg'] ?? '';
        $accessToken = $baseInfo['data']['access_token'] ?? null;
        $employeeId  = $baseInfo['data']['employee_id'] ?? null;
        $openId      = $baseInfo['data']['open_id'] ?? null;
        if (null === $accessToken || null === $openId) {
            throw new \Exception('飞书基础信息获取失败:'.$msg);
        }

        if (null === $employeeId) {
            throw new \Exception('飞书小程序获取用户 user ID权限未开通，请联系管理员');
        }

        $userInfo = FeishuApiService::userInfo($openId, $accessToken);
        if (!is_array($userInfo['data']['user'] ?? null)) {
            $fsMsg = $userInfo['msg'] ?? '';
            throw new \Exception("飞书用户信息获取失败: {$fsMsg}".$msg);
        }
        $feishuId = $userInfo['data']['user']['user_id'] ?? '';

        // 根据手机号获取rms用户信息 并更新openId
        $mobile  = substr($userInfo['data']['user']['mobile'], -11);
        $rmsInfo = (new RmsUserApi)->getUserInfoByMobiles([$mobile]);
        if (empty($rmsInfo['data'])) {
            throw new ResponseHttpException(400001, null, '用户不存在');
        }
        $userInfo = $rmsInfo['data'][0];
        if (mb_strlen($userInfo['feishuUserId'])) {
            //更新飞书userId
            (new RmsUserApi())->setUserFeishuIdNByteUserId($userInfo['id'], ['feishuUserId' => $userInfo['feishuUserId']]);
        }
        $token = AppletEncrypt::getInstance()
                              ->encryptData($siteConfig, $userInfo['id'], $userInfo['username'], $mobile, $feishuId, $ip);

        // TODO 根据请求的appid，来加
//        if (in_array($siteConfig['appId'], [])) {
//            $extCompany = FsCompanyUserModel::checkExt($userInfo['id'] ?? 0, $feishuId ?? '');
//            if (!$extCompany) {
//                // TODO 尝试insert组织
//            }
//        }

        // 记录登录日志
        FsLoginLogModel::add((int)$userInfo['id'], $feishuId, $siteConfig['appId'], $siteConfig['platformName']);

        Log::info("loginByFeishuCode End feishuCode:{$feishuCode}: {$token}");

        return [
            'token' => $token
        ];
    }

}
